package cn.wicking.demo06.config;

import cn.wicking.demo06.entity.User;
import cn.wicking.demo06.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        final SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        final Subject subject = SecurityUtils.getSubject();
        final User principal = (User) subject.getPrincipal();
        if (principal.getPerms()!=null){
            simpleAuthorizationInfo.addStringPermission(principal.getPerms());
        }
        return simpleAuthorizationInfo;
    }


    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        final QueryWrapper<User> query = Wrappers.query();
        query.eq("name",token.getUsername());
        final User user = userMapper.selectOne(query);
        System.out.println(user);
        if (user == null){
            return null;
        }

        final Subject subject = SecurityUtils.getSubject();
        final Session session = subject.getSession();
        session.setAttribute("LoginUser",user);
        //shiro帮我们验证principal 传递到上面授权方法
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
